<?php
set_time_limit(0);

//亚马逊的access key
define('AMAZON_KEY', 'AKIAJ3TIKQKUKM4KQPNQ');
//亚马逊的secret key
define('AMAZON_SECRET', 'HqZ19PB9C77qVoCRIO6xyMOIcj57eYrQNKo4FO+K');
//默认国家。可选值de, com, co.uk, ca, fr, co.jp, it, cn, es
define('AMAZON_COUNTRY', 'com');

//京东的app key
define('JD_KEY', '73584848D0D7A4D61242678B6E130957');
//京东的secret key
define('JD_SECRET', 'e0812e7e399f4711b375e51ed836ff32');
//京东的回调地址
define('JD_CALLBACK', 'http://www.huoguoge.com/admin/index.php?a=import&m=WoguProductImport');

//淘宝的app key
define('TAOBAO_KEY', '21738716');
//淘宝的secret key
define('TAOBAO_SECRET', '013739ed90e75cbaf854d6804935afa6');

class WoguProductImportAction extends CommonAction
{
    public function cjkeyword() {
        $cate_id = intval($_GET['cate_id']);
        header("LOCATION: /admin/index.php?a=docjkeyword&m=WoguProductImport&cate_id={$cate_id}");
    }
    
    public function cjkeyword2() {
        header("LOCATION: /admin/index.php?a=docjkeyword&m=WoguProductImport");
    }
    
    public function docjkeyword() {
        $cate_id = intval($_GET['cate_id']);
        $model = D('GoodsCategory');
        $row = $model->query('SELECT * FROM '.C("DB_PREFIX").'goods_category WHERE cate_type=1 AND parent_id!=0 AND platform=\'cj\' AND cate_id'.(isset($_GET['next']) || $cate_id == 0 ? '>' : '=').$cate_id.' ORDER BY cate_id ASC');
        $value = $r = $row[0];
        if(!$value) {
            exit('商家采集完毕!');
        }
        
        $maxpages = 10;
        $page = max(1, intval($_GET['page']));
        $perpage = 100;
        $pages = intval($_GET['pages']);
        $baseurl = '/admin/index.php?a=docjkeyword&m=WoguProductImport';
        $keyword = $value['short_name'];
        $wid = 7469421;
        
        $array = explode('|',$keyword);
        $jia = trim($array[0]);
        $jiaarr = explode(' ',$jia);
        $strj = '';
        foreach($jiaarr as $jtm){
        	if(!empty($jtm)){
        		$strj .="+".$jtm;
        	}
        }
        if(!empty($array[1])){
        	$jnstr = trim($array[1]);
        	$jianrr = explode(' ',$jnstr);
        	$str = '';
        	foreach($jianrr as $val){
        		if(!empty($val)){
        			$str .= '-'.$val;
        		}
        	}
        }
        $tmp['keywords'] = $strj.$str;
    	$tmp['website-id'] = $wid;
    	$tmp['advertiser-ids'] = 'joined';
        $parm = '';
        foreach($tmp as $key=>$val) {
        	if($parm!='')$parm.="&";
        	$parm.=$key."=".$val;
        }
        
        $url = 'https://product-search.api.cj.com/v2/product-search?records-per-page='.$perpage.'&serviceable-area=US&'.$parm.'&page-number='.$page;
        $str = getResource($url);
        $str = preg_replace('/&#\d+;/', '', $str);
        $xml = simplexml_load_string($str);
        if(!$xml) {
            if(empty($str)) {
                sleep(10);
                $this->error("关键词“{$keyword}”第{$page}/{$pages}页获取出错，重新获取！", "{$baseurl}&page={$page}&pages={$pages}&cate_id={$value['cate_id']}");
                exit();
            } else {
                //ShowMsg("栏目“{$r['typename']}[id={$r['id']}]”获取出错，进入下一栏目！", "{$baseurl}?id={$r['id']}&next=1");
                //exit();
                echo '------'.$str;
                exit;
            }
        }
        //页数的计算。
        $arr = $xml->products->attributes();
        $total = $arr['total-matched'];
        if($total > 0) {
            $num = $arr['records-returned'];
            if($page == 1) {
                $pages = ceil($total/$num);
                $pages = $maxpages > 0 && $pages > $maxpages ? $maxpages : $pages;
            } else {
                $pages = $_GET['pages'];
            }
            
            for($i=0;$i<$num;$i++){
                $code = xml2array($xml->products->product[$i]);
                //////////////////对关键词进行再次过滤///////////////////////////////////////
                $filterKeyword = $code['name'].$code['description'];
                $filterKeyword = strtolower($filterKeyword);
                $flag = true;
                foreach($jiaarr as $keyw){
                    $b = strpos($filterKeyword,$keyw);
                    $flag = $flag&&$b;
                }
        
                $flagjian = true;
                if(!empty($jianrr)){
                    foreach($jianrr as $keyj){
                        $d = strpos($filterKeyword,$keyj);
                        if($d===false){
                            $c = true;
                        }else{
                            $c = false;
                        }
                        $flagjian = $flagjian&&$c;
                    }
                }
                
                //////////////////////////////////////////////////////////////////////////////
                if($flag&&$flagjian){
                    $adid = $code['advertiser-id'];
                    $name = $code['advertiser-name'];
                    $result[$adid] = addslashes($name);
                }
            }
        }
        
        $j=0;
        foreach($result as $key => $val){
            $cts = D('WoguCateCj')->query('SELECT * FROM '.C("DB_PREFIX")."wogu_cate_cj WHERE advid='{$key}' AND cate_id={$cate_id}");
        	if(empty($cts)){
        		D('WoguCateCj')->query('INSERT INTO '.C("DB_PREFIX")."wogu_cate_cj (advid,advname,cate_id) VALUES('{$key}','{$val}','{$cate_id}')");
                echo D('WoguCateCj')->getDbError();
                echo D('WoguCateCj')->getError();
        		$j++;
        	}
        }
        
        if($page >= $pages) {
            $this->success("采集成功，进入下一个栏目！", "{$baseurl}&cate_id={$value['cate_id']}&next=1");
        } else {
            $this->success("[{$value['cate_name']}]添加'$j'个商家[{$page}/{$pages}]","{$baseurl}&page=".(++$page)."&pages={$pages}&cate_id={$value['cate_id']}");
        }
    }
    
    public function import() {
	    require_once(ADMIN_PATH.'/Lib/ORG/jd/config.php');
	    if(isset($_GET['code'])) {
            $token = $jos->fetchAccessToken($_GET['code'], $_GET['state']);
            $_SESSION['token'] = $token;
	    }
	    
	    if(!isset($_GET['run'])) {
	        echo '<a href="/admin/index.php?a=import&m=WoguProductImport&run">开始采集</a>';
	        if(!$_SESSION['token']) {
	            echo '|<a href="'.$jos->getAuthorizeUrl().'">登陆京东</a>';
	        }
	        exit;
	    }
        
        $baseurl = '/admin/index.php?a=import&m=WoguProductImport';
        $maxpages = 0;
        $perpage = 20;
        $id = intval($_GET['id']);
        $page = max(1, intval($_GET['page']));
        $pages = max(1, intval($_GET['pages']));
        $index = intval($_GET['index']);
        $jumpnext = true;
        $model = D('GoodsCategory');
        $row = $model->query('SELECT * FROM '.C("DB_PREFIX").'goods_category WHERE cate_type=1 AND parent_id!=0 AND cate_id'.(isset($_GET['next']) || $id == 0 ? '>' : '=').$id.' ORDER BY cate_id ASC');
        $value = $r = $row[0];
        if(!$value) {
            $this->success('产品采集完毕!', $baseurl);
        }
        $typeid = $value['cate_id'];
        //jd,amazon
        $keywordarr = explode('|', $value['short_name']);
        $searchkeyword = $keywordarr[0];
        $addkeywords = explode(' ', $searchkeyword);
        $subkeywords = isset($keywordarr[1]) ? explode(' ', $keywordarr[1]) : array();

        if($value['platform'] == 'gn') {
            if($index == 0) {
                $value['platform'] = 'jd';
                $jumpnext = false;
            } elseif($index == 1) $value['platform'] = 'amazon';
        }

        if($value['platform'] == 'cj') {
            $wid = 7469421;
            $cjid = intval($_GET['cjid']);
            $advs = D('WoguCateCj')->query('SELECT * FROM '.C("DB_PREFIX")."wogu_cate_cj WHERE cate_id={$typeid} AND id".(isset($_GET['cjnext']) || $cjid == 0 ? '>' : '=').$cjid.' ORDER BY id ASC LIMIT 0,1');
            if(empty($advs)) {
                $url = "{$baseurl}&id={$r['cate_id']}&run";
                if($jumpnext) $url .= '&next=1';
                else $url .= '&index='.(++$index);
                $this->success("栏目“{$r['cate_name']}[id={$r['cate_id']}]”获取完成！!", $url);
                exit;
            }
            $adv = $advs[0];

    		$search_keyword = trim($value['short_name']);
    		$array = explode('|',$search_keyword);
    		$jia = trim($array[0]);
    		$jiaarr = explode(' ',$jia);
    		$strj = '';
    		foreach($jiaarr as $jtm){
    			if(!empty($jtm)){
    				$strj .="+".$jtm;
    			}
    		}
    		if(!empty($array[1])){
    			$jnstr = trim($array[1]);
    			$jianrr = explode(' ',$jnstr);
    			$strjian = '';
    			foreach($jianrr as $val){
    				if(!empty($val)){
    					$strjian .= '-'.$val;
    				}
    			}
    		}
    		$tmp['keywords'] = $strj.$strjian;
    		$tmp['website-id'] = $wid;
    		$tmp['advertiser-ids'] = $adv['advid'];
        	$parm = '';
        	foreach($tmp as $key=>$val) {
        		if($parm!='')$parm.="&";
        		$parm.=$key."=".$val;
        	}
        	$url = 'https://product-search.api.cj.com/v2/product-search?records-per-page='.$perpage.'&serviceable-area=US&'.$parm.'&page-number='.$page;
        	$str = getResource($url);
        	$str = preg_replace('/&#\d+;/', '', $str);
        	$xml = simplexml_load_string($str);
        	if(!$xml) {
        	    if(empty($str)) {
        	        sleep(10);
                    $this->error("栏目“{$r['cate_name']}[id={$r['cate_id']}]”获取出错，重新获取！", "{$baseurl}&id={$r['id']}&page={$page}&pages={$pages}&run&cjid={$adv['id']}&index={$index}");
                } else {
                    //ShowMsg("栏目“{$r['typename']}[id={$r['id']}]”获取出错，进入下一栏目！", "{$baseurl}?id={$r['id']}&next=1");
                    //exit();
                    echo '------'.$str;
                }
        	}
        	$arr = $xml->products->attributes();
        	$total = $arr['total-matched'];
            if($total > 0) {
                $num = $arr['records-returned'];
                if($page == 1) {
                    $pages = ceil($total/$num);
                    $pages = $maxpages > 0 && $pages > $maxpages ? $maxpages : $pages;
                } else {
                    $pages = $_GET['pages'];
                }
                
            	for($i=0;$i<$num;$i++){
            	    $code = xml2array($xml->products->product[$i]);
            	    //////////////////对关键词进行再次过滤///////////////////////////////////////
            		$filterKeyword = $code['name'].$code['description'];
            		$filterKeyword = strtolower($filterKeyword);
            		$flag = true;
            		foreach($jiaarr as $keyw){
            			$b = strpos($filterKeyword,$keyw);
            			$flag = $flag&&$b;
            		}
        
            		$flagjian = true;
            		if(!empty($jianrr)){
            			foreach($jianrr as $keyj){
            				$d = strpos($filterKeyword,$keyj);
            				if($d===false){
            					$c = true;
            				}else{
            					$c = false;
            				}
            				$flagjian = $flagjian&&$c;
            			}
            		}
            		
                	//////////////////////////////////////////////////////////////////////////////
                	if($flag&&$flagjian){
                	    $name = addslashes(str_replace('"', '', trim($code['name'], '-')));
                	    $mycjid = substr(md5($code['ad-id'].$name),8,16);
                	    $imginfo = getimagesize($code['image-url']);
                        $product = array(
                            'cate_id' => $typeid,
                            'title' => $name,
                            'keyword' => $value['short_name'],
                            'source' => 'cj',
                            'price' => $code['price'],
                            'content' => addslashes(trim(str_replace('&apos','',$code['description']))),
                            'img' => $code['image-url'],
                            'redirecturl' => $code['buy-url'],
                            'status' => 1,
                            'cjid' => $mycjid,
                            'width' => $imginfo[0],
                            'height' => $imginfo[1]
                        );
                        if(intval($product['price'])!=0){
                            $oldproduct = D('WoguProduct')->query('SELECT * FROM '.C("DB_PREFIX").'wogu_product WHERE cjid=\''.$mycjid.'\'');
                    		if(!empty($oldproduct)) {
                    		    $product['id'] = $oldproduct[0]['id'];
                    		    D('WoguProduct')->save($product);
                    		} else {
                    		    D('WoguProduct')->add($product);
                    		}
                    	}
                	}
                }
            }
            
            //此商家获取完毕
            if($page >= $pages) {
                $this->success("栏目“{$r['cate_name']}[id={$r['cate_id']}]”=>“商家[{$adv['advname']}]”获取完成！", "{$baseurl}&id={$r['cate_id']}&run&cjid={$adv['id']}&cjnext&index={$index}");
            } else {//此商家有下一页
                $this->success("栏目“{$r['cate_name']}[id={$r['cate_id']}]”=>“商家[{$adv['advname']}]”第{$page}/{$pages}页获取完成，进入下一页！", "{$baseurl}&run&id={$r['cate_id']}&page=".(++$page)."&pages={$pages}&cjid={$adv['id']}&index={$index}");
            }
            exit;
        } elseif($value['platform'] == 'jd') {
            try {
                $req = new WareProductSearch();
                $req->isLoadAverageScore = false;
                $req->isLoadPromotion  = false;
                $req->sort = 1;
                $req->page = $page;
                $req->pageSize  = $perpage;
                $req->client = 'm';
                $req->keyword  = $searchkeyword;
                $resp = $jos->execute($req, $_SESSION['token']->access_token);
                if($resp->code == 0) {
                    $plist = $resp->searchProductList;
                    $total = $plist->wareCount;
                    $pages = ceil($total/$req->pageSize);
                    $items = $plist->wareInfo;
                    foreach($items as $v) {
                        $imginfo = getimagesize($v->imageUrl);
                        $product = array(
                            'cate_id' => $typeid,
                            'title' => $v->wareName,
                            'keyword' => $searchkeyword,
                            'source' => '京东',
                            'price' => $v->jdPrice,
                            'content' => $v->adWord,
                            'img' => $v->imageUrl,
                            'redirecturl' => 'http://item.jd.com/'.$v->skuId.'.html',
                            'status' => 1,
                            'width' => $imginfo[0],
                            'height' => $imginfo[1]
                        );
                        $row = $model->query('SELECT * FROM '.C("DB_PREFIX")."wogu_products_jd WHERE skuId='{$v->skuId}'");
                        if(empty($row)) {
                            $aid = D('WoguProduct')->add($product);
                            if($aid) {
                                $log = array(
                                    'aid' => $aid,
                                    'skuId' => $v->skuId,
                                    'jdPrice' => $v->jdPrice,
                                    'martPrice' => $v->martPrice,
                                    'wareName' => $v->wareName,
                                    'adWord' => $v->adWord
                                );
                                if(!D('WoguProductsJd')->add($log)) {
                                    echo D('WoguProductsJd')->getDbError();
                                    echo D('WoguProductsJd')->getError();
                                    exit('xxx');
                                }
                            }
                        } else {
                            $product['id'] = $row[0]['aid'];
                            D('WoguProduct')->save($product);
                        }
                    }
                }
            } catch(JosApiException $e) {
                print_r($e);exit;
            }
        } elseif($value['platform'] == 'amazon') {
            require_once(ADMIN_PATH.'/Lib/ORG/AmazonECS.class.php');
            try {
                $client = new AmazonECS(AMAZON_KEY, AMAZON_SECRET, AMAZON_COUNTRY, 'All');
                $productsinfo = $client->returnType(AmazonECS::RETURN_TYPE_ARRAY)->category('All')->responseGroup('Large')->page($page)->search($searchkeyword);
                if(isset($productsinfo['Items']['Item'])){
                    $pages = $productsinfo['Items']['TotalPages'];
                    $pages = $pages > 5 ? 5 : $pages;
                    $items = $productsinfo['Items']['Item'];
                    foreach($items as $v) {
                        if(!is_array($v)) {
                            continue;
                        }
        
                        $title = $v['ItemAttributes']['Title'];
                        $miaoshu = $v['EditorialReviews']['EditorialReview']['Content'];
                        $testtitle = strtolower($title);
                        $testmiaoshu = strtolower($miaoshu);
                        foreach($addkeywords as $vv) {
                            $vv = strtolower($vv);
                            if(strpos($testtitle, $vv) === false && strpos($testmiaoshu, $vv) === false) {
                                continue 2;
                            }
                        }
                        
                        if(!empty($subkeywords)) {
                            foreach($subkeywords as $vv) {
                                $vv = strtolower($vv);
                                if(strpos($testtitle, $vv) !== false && strpos($testmiaoshu, $vv) !== false) {
                                    continue 2;
                                }
                            }
                        }
                        
                        if( isset($v['Offers']['Offer']['OfferListing']['Price']['Amount']) ) {
                            $jiage = $v['Offers']['Offer']['OfferListing']['Price']['Amount'] / 100;
                        } elseif( isset($v['ItemAttributes']['ListPrice']['Amount']) ) {
                            $jiage = $v['ItemAttributes']['ListPrice']['Amount'] / 100;
                        }
                        
                        $jiage = intval($jiage);
                        if(!isset($jiage) || $jiage <= 0) {
                            continue;
                        }
                        
                        $imginfo = getimagesize($v['MediumImage']['URL']);
                        $product = array(
                            'cate_id' => $typeid,
                            'title' => $title,
                            'keyword' => $searchkeyword,
                            'source' => '亚马逊',
                            'price' => $jiage,
                            'content' => $miaoshu,
                            'img' => $v['MediumImage']['URL'],
                            'redirecturl' => $v['DetailPageURL'],
                            'status' => 1,
                            'width' => $imginfo[0],
                            'height' => $imginfo[1]
                        );
                        
                        $row = $model->query('SELECT * FROM '.C("DB_PREFIX")."wogu_products_amazone WHERE ASIN='{$v['ASIN']}'");
                        if(empty($row)) {
                            $aid = D('WoguProduct')->add($product);
                            if($aid) {
                                $log = array(
                                    'aid' => $aid,
                                    'ASIN' => $v['ASIN'],
                                    'Binding' => $v['ItemAttributes']['Binding'],
                                    'Brand' => $v['ItemAttributes']['Brand'],
                                    'Color' => $v['ItemAttributes']['Color'],
                                    'ProductTypeName' => $v['ItemAttributes']['ProductTypeName']
                                );
                                if(!D('WoguProductsAmazone')->add($log)) {
                                    echo D('WoguProductsAmazone')->getDbError();
                                    echo D('WoguProductsAmazone')->getError();
                                    exit('xxx');
                                }
                            }
                        } else {
                            $product['id'] = $row[0]['aid'];
                            D('WoguProduct')->save($product);
                        }
                    }
                }
            } catch(Exception $e) {
                $this->success('网络连接异常请重试！', '/admin/index.php?a=import&m=WoguProductImport');
                exit;
            }
        }
        
        //此栏目获取完毕
        if($page >= $pages) {
            $url = "{$baseurl}&id={$r['cate_id']}&run";
            if($jumpnext) $url .= '&next=1';
            else $url .= '&index='.(++$index);
            $this->success("栏目“{$r['cate_name']}[id={$r['cate_id']}]”获取完成！", $url);
        } else {//此栏目有下一页
            $this->success("栏目“{$r['cate_name']}[id={$r['cate_id']}]”第{$page}/{$pages}页获取完成，进入下一页！", "{$baseurl}&run&id={$r['cate_id']}&page=".(++$page)."&pages={$pages}&index={$index}");
        }
    }
}

function getResource($url){
	$ch = curl_init($url);
	curl_setopt($ch,CURLOPT_HTTPHEADER,array (
			"Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
			"Accept-Encoding:gzip, deflate",
			"Accept-Language:zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3",
			"Authorization:0081e40c817a713128a0df8041797e1ada4f860092f40a91def1b4be280b05c1a9bfc82a37c145fe50fff5f96a1a3e8a4fa26e46e6d6d0672901459a284e4e54f3/75a06466d8d02ab9653e2172a9a8367f1ee6f61c1e5e780d128c206c38d724b1dd04d062ad81f0de337f8ca47b16844bc0499822de63b042ad7992e1ace08629",
			 "Connection:keep-alive",
			 "Host:advertiser-lookup.api.cj.com",
			 "User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0"
		 ));
	curl_setopt($ch, CURLOPT_HEADER, 0);            //不取得返回头信息
	curl_setopt($ch, CURLOPT_TIMEOUT, 30);
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	$result = curl_exec($ch);
	curl_close ( $ch );
	return $result;
}

function xml2array($xmlObject){
	$out = array();
	 foreach ( (array) $xmlObject as $index => $node )
		 $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;
	return $out;
 }